package service

import (
	"fmt"
	"io/ioutil"
	"choujiang/common/db"
	"choujiang/common/models"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"choujiang/common/utils"
	"time"
)

const (
	PREPARE_KEY             = "MpKey::invite_prepare_notice" //待发送通知
	DAILI_DAILY_ACTIVE_USER = "MpKey::daili_daily_active_"   //代理每日活跃用户
)

//通知代理，邀请新的用户
func MpDlInviteNew(dlId, uId int64) bool {
	dlUser := model.GetDlById(dlId)
	if dlUser == nil || dlUser.MiniOpenId == "" {
		return false
	}
	user := model.GetUserByUid(uId)
	if user == nil || user.NickName == "" {
		return false
	}
	resp, err := http.PostForm("https://mp.leyougame.cc/mp_message",
		url.Values{"nickname": {user.NickName}, "open_id": {dlUser.MiniOpenId}, "act": {"invite"}})
	if err != nil {
		err = fmt.Errorf("[MpDlInviteNew]failed, err: %+v\n", err)
		fmt.Printf("[MpDlInviteNew]failed, err: %+v\n", err)
		return false
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		err = fmt.Errorf("[MpDlInviteNew]failed, http.Status: %s", resp.Status)
		fmt.Printf("[MpDlInviteNew]failed, http.Status: %s", resp.Status)
		return false
	}
	_, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		err = fmt.Errorf("[MpDlInviteNew]failed, err: %+v\n", err)
		fmt.Printf("[MpDlInviteNew]failed, err: %+v\n", err)
		return false
	}
	return true
}

//准备给代理发送消息通知
func PrepareNotice(dlId, uId int64) {
	field := strconv.FormatInt(dlId, 10) + "_" + strconv.FormatInt(uId, 10)
	cmd := db.MainRedisClient.HExists(PREPARE_KEY, field)
	if !cmd.Val() {
		//将待发送的消息记录放入redis队列
		bcmd := db.MainRedisClient.HSet(PREPARE_KEY, field, field)
		if !bcmd.Val() {
			fmt.Printf("----[PrepareNotice] err: %s", bcmd.String())
		}
	}
	return
}

//处理队列中需要发送的消息
func DealPrepareNotice() {
	cmd := db.MainRedisClient.HGetAll(PREPARE_KEY)
	noticeMap := cmd.Val()
	for k, v := range noticeMap {
		slice := strings.Split(v, "_")
		dlId, _ := strconv.ParseInt(slice[0], 10, 64)
		uId, _ := strconv.ParseInt(slice[1], 10, 64)
		if MpDlInviteNew(dlId, uId) { //通知成功
			//从队列中删除
			db.MainRedisClient.HDel(PREPARE_KEY, k)
		}
	}
}

//记录代理的活跃用户数量
func LogActiveUser(dlId, uId int64) {
	key := DAILI_DAILY_ACTIVE_USER + strconv.FormatInt(dlId, 10) + "_" + utils.TodayUnix()
	member := strconv.FormatInt(uId, 10)
	cmd := db.MainRedisClient.SIsMember(key, member)
	if !cmd.Val() { //未记录
		db.MainRedisClient.SAdd(key, member)         //记录活跃用户
		db.MainRedisClient.Expire(key, time.Hour*25) //过期时间一天
		db.Mgo.RecordActiveUser(strconv.FormatInt(dlId, 10), utils.TodayUnix())
	}
	return
}

//给代理发送二维码更换通知
func AlertGroupQrcode() {
	var (
		nowTime   int64
		limitTime int64
	)
	nowTime = time.Now().Unix()
	limitTime = nowTime - 216000
	users := make([]model.HzwUser, 0)
	err := db.MysqlEngine.Where("status = ? and group_update_at < ? and group_update_at > 0", 2, limitTime).Find(&users)
	if err != nil {
		fmt.Printf("AlertGroupQrcode err %s", err)
	}
	fmt.Printf("users ----------- %v+", users)
	if len(users) > 0 {
		for i := 0; i < len(users); i++ {
			resp, err := http.PostForm("https://mp.leyougame.cc/mp_message",
				url.Values{"open_id": {users[i].MiniOpenId}, "dlname": {utils.DecodeNickName(users[i].NickName)}, "act": {"qr_code"}, "updated": {utils.FormatDate(users[i].GroupUpdateAt)}, "ended": {utils.FormatDate(users[i].GroupUpdateAt + 259200)}})
			if err != nil {
				err = fmt.Errorf("[AlertGroupQrcode]failed, err: %+v\n", err)
				fmt.Printf("[AlertGroupQrcode]failed, err: %+v\n", err)
			}
			defer resp.Body.Close()
			if resp.StatusCode != http.StatusOK {
				err = fmt.Errorf("[AlertGroupQrcode]failed, http.Status: %s", resp.Status)
				fmt.Printf("[AlertGroupQrcode]failed, http.Status: %s", resp.Status)
			}
			_, err = ioutil.ReadAll(resp.Body)
			if err != nil {
				err = fmt.Errorf("[AlertGroupQrcode]failed, err: %+v\n", err)
				fmt.Printf("[AlertGroupQrcode]failed, err: %+v\n", err)
			}
		}
	}
}
